// pages/public/article_detail/article_detail.js
const app = getApp()
import {
    _get,
    _post,
    _headerGet,
    _headerPost,
    config
} from '../../../utils/httpUtils.js'
const RSA = require("../../../utils/wx_rsa.js");

Page({
    data: {
        ip: config.host,
        navbarData: {
            showCapsule: 1, //是否显示左上角图标
            title: '' //导航栏 中间的标题
        },
        height: app.globalData.height,
        id: '',
        showComment: true,
        purchase: false,
        buyBtn: '',
        buyNumber: 1, //默认商品数量
        maskSty: "none",
        showTop: true,
        html: "",
        commentWidth: 330,
        articleHeight: 800,
        animationData: "",
        goods: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(option) {
        if (option.scene) {
            let scene = option.scene.split('--'); // 通过二维码扫码进来的参数
            scene[0] == 1 ? this.getDetail(scene[1]) : wx.redirectTo({
                url: `/pages/activity/line001/detail?id=${scene[1]}&uid=${scene[2]}`
            })
        } else {
            this.getDetail(option.id)
            this.data.id = option.id //储存文章 id
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        let _this = this;
        wx.createSelectorQuery().select(`.article`).boundingClientRect(function(rect) {
            if (rect.height < 800) {
                _this.setData({
                    showAllHide: true
                })
            }
        }).exec()
    },
    pageScrollToBottom: function(e) { //页面滚动
        wx.createSelectorQuery().select(`.${e.currentTarget.dataset.position}`).boundingClientRect(function(rect) {
            if (rect.height < 667) return
            wx.pageScrollTo({
                scrollTop: rect.height,
                duration: 500
            })
        }).exec()
    },

    getDetail(id) { //获取文章详情
        _headerGet('/api/article/detail', {
            'id': id
        }, res => {
            // console.log(res.data)
            if (res.data.code == 1) {
                this.setData({
                    nodes: res.data.data,
                    html: res.data.data.article_a_content.replace(/\<img/g, `<img style="width:99%; margin:10px auto; height:auto; display:block"`),
                    navbarData: {
                        showCapsule: 1, //是否显示左上角图标
                        title: `${res.data.data.article_a_title}`
                    }

                })
                // 如果投票选项有
                if (res.data.data.article_vote_options) {
                    this.setData({
                        vote: {
                            title: res.data.data.article_a_vote_title,
                            voteNum: res.data.data.article_a_is_vote,
                            voteCount: res.data.data.article_a_is_vote_count,
                            percent: res.data.data.article_a_is_vote_percent,
                            option: res.data.data.article_vote_options
                        }
                    })
                }
                // 如果是商品,处理商品逻辑
                if (res.data.data.article_a_is_goods != '0') {
                    // console.log(res.data.data.article_a_is_goods)
                    this.setData({
                        purchase: true
                    })
                    this.getGoodsAttr(res.data.data.article_a_id);
                }
                wx.stopPullDownRefresh()
            } else {
                wx.showModal({
                    title: '提示',
                    content: res.data.msg,
                    showCancel: false
                })
                wx.stopPullDownRefresh()
                return
            }
        })
    },
    getGoodsAttr(article_id) { //获取商品属性
        _post('/api/goods/get_goods_detail', {
            article_id: article_id
        }, res => {
            if (res.data.code == 1) {
                this.setData({
                    goods: res.data.data
                })
                let detail = res.data.data.goodsDetail;
                if (detail.g_spec_format != '') {
                    let child = JSON.parse(detail.g_spec_format)
                    let defChioce = ''
                    //设置属性的状态，并默认选中第一个
                    for (let i = 0; i < child.length; i++) {
                        for (let j = 0; j < child[i].spec_value.length; j++) {
                            if (j == 0) {
                                child[i].spec_value[j].active = true
                                defChioce = defChioce + child[i].spec_id + ':' + child[i].spec_value[j].spec_value_id + ';';
                            } else {
                                child[i].spec_value[j].active = false
                            }
                        }
                    }
                    this.defaultType(defChioce) //设置默认选项
                    this.setData({
                        g_spec_format: child,
                    })
                }
            } else {
                wx.showToast({
                    title: res.data.msg,
                    duration: 2000,
                    icon: 'none'
                })
            }
        })
    },
    defaultType(choice) { //根据结果判断判断商品类型
        let skuArr = this.data.goods.goodsSku
        for (let k = 0; k < skuArr.length; k++) {
            if (skuArr[k].attr_value_items == choice.substring(0, choice.length - 1)) {
                this.setData({
                    goodsType: skuArr[k]
                })
            }
        }
    },
    labelItemTap(e) {
        // 取消该分类下的子栏目所有的选中状态
        let childs = this.data.g_spec_format[e.currentTarget.dataset.propertyindex].spec_value;
        for (let i = 0; i < childs.length; i++) {
            this.data.g_spec_format[e.currentTarget.dataset.propertyindex].spec_value[i].active = false;
        }
        // 设置当前选中状态
        this.data.g_spec_format[e.currentTarget.dataset.propertyindex].spec_value[e.currentTarget.dataset.propertychildindex].active = true;
        //获取所有的选中规格尺寸数据
        let needSelectNum = this.data.g_spec_format.length;
        let curSelectNum = 0;
        let propertyChildIds = "";
        let propertyChildNames = "";
        //得到选中结果
        for (let i = 0; i < this.data.g_spec_format.length; i++) {
            let childs = this.data.g_spec_format[i].spec_value;
            for (let j = 0; j < childs.length; j++) {
                if (childs[j].active) {
                    curSelectNum++;
                    propertyChildIds = propertyChildIds + this.data.g_spec_format[i].spec_id + ":" + childs[j].spec_value_id + ";"
                    propertyChildNames = propertyChildNames + childs[j].spec_name + ":" + childs[j].spec_value_name + ";"
                }
            }
        }
        //根据结果判断判断商品类型
        let skuArr = this.data.goods.goodsSku
        for (let k = 0; k < skuArr.length; k++) {
            if (skuArr[k].attr_value_items == propertyChildIds.substring(0, propertyChildIds.length - 1)) {
                this.setData({
                    goodsType: skuArr[k]
                })
            }
        }
        this.setData({
            g_spec_format: this.data.g_spec_format
        })
    },
    //数量减少
    numJianTap: function() {
        if (this.data.buyNumber > 1) {
            let currentNum = this.data.buyNumber;
            currentNum--;
            this.setData({
                buyNumber: currentNum
            })
        }
    },
    //数量增加
    numJiaTap: function() {
        if (this.data.buyNumber < this.data.goods.goodsDetail.goods_stock) {
            let currentNum = this.data.buyNumber;
            currentNum++
            this.setData({
                buyNumber: currentNum
            })
        }
    },

    buyNow() { // 立即购买
        if (this.data.goodsType.stock == 0) {
            wx.showToast({
                title: '库存不足哦',
                icon: 'none'
            })
            return
        }
        let _data = {
            c_client: 'weixinSmall',
            type: 'buyNow',
            skuId: this.data.goodsType.sku_id,
            num: this.data.buyNumber
        }
        wx.navigateTo({
            url: '/pages/public/confirm-order/index?data=' + JSON.stringify(_data)
        })
    },

    joinCart() { // 加购

        if (this.data.goodsType.stock == 0) {
            wx.showToast({
                title: '库存不足哦',
                icon: 'none'
            })
            return
        }
        let _data = {
            c_client: 'weixinSmall',
            a_id: this.data.id,
            sku_id: this.data.goodsType.sku_id,
            num: this.data.buyNumber
        }
        let that = this; //更改 this 指向
        _headerPost('/api/Cart/addCart', _data, res => {
            wx.showToast({
                title: res.data.msg,
                duration: 2000,
                icon: 'success',
                success() {
                    that.closePopupTap()
                }
            })
        })
    },

    handOver(event) { // 获取属性
        let currentId = event.currentTarget.dataset.id;
        this.setData({
            cate_id: currentId,
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        this.getDetail(this.data.id)
    },

    _navback() { //返回
        wx.navigateBack()
    },

    closePopupTap() {
        this.setData({
            maskSty: 'none'
        })
    },

    showPopupTap() {
        this.setData({
            maskSty: 'block'
        })
    },

    previewImage(e) {
        let currentSrc = e.currentTarget.dataset.src;
        let currentSrcArray = e.currentTarget.dataset.srcarr;
        wx.previewImage({
            current: currentSrc, // 当前显示图片的http链接
            urls: [currentSrcArray] // 需要预览的图片http链接列表
        })
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },
    showBuyBtn() {
        this.commentFocus()
    },

    commentFocus(e) { //键盘聚焦
        this.setData({
            showComment: false,
            commentWidth: 530,
            buyBtn: true
        })
    },

    commentBlur(e) { //键盘失去焦点
        this.setData({
            showComment: true,
            commentWidth: 330,
            buyBtn: ''
        })
    },
    comment(e) { //评论提交
        let _data = {
            'ac_type': 2,
            'id': this.data.id,
            'content': e.detail.value.content
        }
        console.log(_data)
        _headerPost('/api/comment/addComment', _data, res => {
            // console.log(res.data)
            if (res.data.code == 1) {
                this.getDetail(this.data.id)
                wx.showToast({
                    title: res.data.msg,
                    icon: 'success',
                    duration: 1000
                })
                this.setData({
                    tmpStorage: '' //置空评论框
                })
            } else {
                wx.showToast({
                    title: res.data.msg,
                    duration: 2000,
                    icon: 'none'
                })
            }
        })
    },
    replyComment(e) { // 测试二级评论  ````````````` 已失效
        let _data = {
            'ac_type': 2,
            'content': '有空一起去玩啊~',
            'id': this.data.nodes.article_a_id,
            'u_comment_id': e.currentTarget.dataset.id
        }
        _headerPost('/api/comment/addComment', _data, res => {
            // console.log(res.data)
            if (res.data.code == 1) {
                this.setData({
                    nodes: this.data.nodes
                })
            } else {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    },
    likes(e) { //文章点赞
        let animation = wx.createAnimation({
            duration: 600,
            timingFunction: "ease",
            delay: 0,
            transformOrigin: "50% 50%",
        })
        animation.scale(1.5, 1.5).rotate(30).step();
        animation.scale(1, 1).rotate(0).step();
        this.setData({
            animationData: animation.export()
        })


        let _isZan = this.data.nodes.article_a_is_zan;
        let _data = {
            'type': 1,
            'id': e.currentTarget.dataset.acid
        }
        if (_isZan == 1) {
            this.data.nodes.article_a_is_zan = 0
            this.data.nodes.article_zan_count--
        } else {
            this.data.nodes.article_a_is_zan = 1
            this.data.nodes.article_zan_count++
        }
        _headerPost('/api/zan/zan', _data, res => {
            if (res.data.code == 1) {
                this.setData({ // 点赞重载数据
                    nodes: this.data.nodes
                })
                wx.showToast({
                    title: res.data.msg,
                    icon: 'success',
                    duration: 2000
                })
            } else if (res.data.code != '-2') {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    },

    collection(e) { //收藏
        let _isCollect = this.data.nodes.article_a_is_collect;
        let _data = {
            'type': RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(`article_admin`)),
            'id': RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(`${e.currentTarget.dataset.acid}`)),
            'c_client': RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(`weixinSmall`))
        }
        if (_isCollect == 1) {
            _headerPost("/api/article/cancel_user_collect", _data, res => {
                if (res.data.code == 1) {
                    this.data.nodes.article_a_is_collect = 0;
                    this.setData({ // 重载数据
                        nodes: this.data.nodes
                    })
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'success',
                        duration: 2000
                    })
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000
                    })
                }
            })
            return
        }
        _headerPost("/api/article/add_user_collect", _data, res => {
            if (res.data.code == 1) {
                this.data.nodes.article_a_is_collect = 1;
                this.setData({ // 重载数据
                    nodes: this.data.nodes
                })
                wx.showToast({
                    title: res.data.msg,
                    icon: 'success',
                    duration: 2000
                })
            } else {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    },

    userlike(e) { // 一级用户评论点赞
        let dataset = e.currentTarget.dataset;
        let _data = {
            'type': 3,
            'id': dataset.id
        }
        let _isZan = this.data.nodes.commentList[dataset.index].is_zan;
        if (_isZan == 1) {
            this.data.nodes.commentList[dataset.index].is_zan = 0;
            this.data.nodes.commentList[dataset.index].zan_count--;
        } else {
            this.data.nodes.commentList[dataset.index].is_zan = 1;
            this.data.nodes.commentList[dataset.index].zan_count++;
        }
        _headerPost('/api/zan/zan', _data, res => {
            if (res.data.code == 1) {
                this.setData({ // 点赞重载数据
                    nodes: this.data.nodes
                })
                wx.showToast({
                    title: res.data.msg,
                    icon: 'success',
                    duration: 2000
                })
            } else if (res.data.code != '-2') {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 2000
                })

            }
        })
    },
    tread(e) { // 评论踩
        let dataset = e.currentTarget.dataset;
        let _isTread = this.data.nodes.commentList[dataset.index].is_tread;
        if (_isTread == 1) {
            this.data.nodes.commentList[dataset.index].is_tread = 0;
        } else {
            this.data.nodes.commentList[dataset.index].is_tread = 1;
        }
        let _data = {
            'c_client': RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(`weixinSmall`)),
            'id': RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(`${e.currentTarget.dataset.id}`))
        }
        _headerPost('/api/article/article_comment_tread', _data, res => {
            if (res.data.code == 1) {
                this.setData({ // 重载数据
                    nodes: this.data.nodes
                })
                wx.showToast({
                    title: res.data.msg,
                    duration: 2000
                })
            }
        })
    },
    showAll() {
        let _hei = this.data.articleHeight
        if (_hei >= 800) {
            this.setData({
                articleHeight: 'auto'
            })
        } else {
            this.setData({
                articleHeight: '800'
            })
        }
    },
    // 投票
    votePoll(e) {
        let _data = {
            'av_states': RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(`${e.currentTarget.dataset.type}`)),
            'a_id': RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(`${this.data.id}`)),
            'c_client': RSA.hex2b64(RSA.KEYUTIL.getKey(app.globalData.publicKey).encrypt(`weixinSmall`))
        }
        _headerPost('/api/article/article_vote', _data, res => {
            // console.log(res.data)
            if (res.data.code == 1) {
                wx.showToast({
                    icon: 'success',
                    title: res.data.msg
                })
                this.setData({
                    vote: {
                        title: this.data.vote.title,
                        voteNum: e.currentTarget.dataset.type,
                        percent: res.data.data.percent,
                        option: this.data.vote.option,
                        voteCount: res.data.data.count_sum
                    }
                })
            } else {
                wx.showToast({
                    title: res.data.msg,
                    icon: "none"
                })
            }
        })
    },

    onPageScroll: function(e) { // 滚动监听返回顶部按钮
        if (e.scrollTop >= 1000) {
            this.setData({
                showTop: false
            })
        } else if (e.scrollTop < 1000) {
            this.setData({
                showTop: true
            })
        }
    },

    scrollTop() {
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 500
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        return {
            title: `${this.data.nodes.article_a_title}`,
            imageUrl: `${this.data.nodes.article_a_main_pic}`,
        }
    }
})